var fs = require('fs');
var express = require('express');
var multer = require('multer')
var router = express.Router();
var debug = require('debug')('rlcas:collect');
var path = require('path');
var dbData = require('../db');
var config = require('../config');
var tools = require('../tools');
var logger = require('./logger');
var img = fs.readFileSync(config.imgPath, 'binary');

// 基础数据处理
router.get('/:id', function (req, res) {
  res.writeHead(200, { 'Content-Type': 'image/png' });
  res.write(img, 'binary');
  res.end()
  var id = req.params.id;
  if (dbData[id]) logger.logData(id, req.data, tools.ip(req));
});


// 多个数据或者文件处理
router.post('/:id', multer({
  limits: {
    files: 1,
    fileSize: 1024 * 256  // 256kb
  },
  fileFilter: function (req, file, cb) {
    var id = req.params.id;
    if (dbData[id]) cb(null, false)
    //  cb(null, false)
    var array = file.originalname.split('.')
    cb(null, array[array.length - 1] === 'txt')
    //  cb(new Error('I don\'t have a clue!'))
  },
  storage: multer.diskStorage({
    destination: function (req, file, cb) {
      var filePath = path.join(config.logsFile, req.params.id, req.data.env)
      tools.mkdir(filePath)
      cb(null, filePath)
    },
    filename: function (req, file, cb) {
      cb(null, req.data.t + '-' + Date.now() + '-' + Math.random().toString().substr(2, 6) + '.txt')
    }
  })
}).single('xt_logfile'), function (req, res) {
  res.writeHead(200, { 'Content-Type': 'image/png' });
  res.write(img, 'binary');
  res.end()
  var id = req.params.id;
  if (dbData[id] && req.data.xt_logdata) logger.logDatas(id, req.data, tools.ip(req));
});

// 用户手动上次日志
router.post('/:id/logdebug', function (req, res) {
  res.writeHead(200, { 'Content-Type': 'image/png' });
  res.write(img, 'binary');
  res.end()
  var id = req.params.id;
  if (dbData[id] && req.data.xt_logdata) logger.logdebug(id, req.data, tools.ip(req));
});

module.exports = router;